package com.example.util.excelListener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.example.entity.ContractVO;
import com.example.service.contractManage.ContractSigningService;

import java.util.ArrayList;
import java.util.List;

/**
 * ----MaxCV工程师---
 *
 * @author wangbiao
 * @date2024/12/6
 * @desc
 */
public class ContractVOListener extends AnalysisEventListener<ContractVO> {

    /**
     * 每隔5条存储数据库,然后清理list,方便回收
     * @param contractVO
     * @param analysisContext
     */
    private static final int BATCH_COUNT = 5;

    private ContractSigningService contractSigningService;

    /**
     * 缓存的数据
     */
    private List<ContractVO> cachedDataList = new ArrayList<>(BATCH_COUNT);
    public ContractVOListener(ContractSigningService contractSigningService){
        this.contractSigningService = contractSigningService;
    }



    @Override
    public void invoke(ContractVO data, AnalysisContext context) {
        // invoke方法每读取到一个数据,就调用一次,就像集合中添加数据
        cachedDataList.add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size()>= BATCH_COUNT){
            saveData();
            // 完成存储清理list
            cachedDataList.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }
    /**
     * 存储数据到数据库
     */
    private void saveData() {
        contractSigningService.insertBatch(cachedDataList);
    }
}
